﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace Soothe.UI
{
    public partial class Form1 : Form
    {
        const int _estimatedHours = 16;

        public Form1()
        {
            InitializeComponent();

            this.chart1.ChartAreas[0].AxisY.Minimum = 0;
            this.chart1.ChartAreas[0].AxisY.Maximum = 1;

            this.chart1.ChartAreas[0].AxisY.LabelStyle.Format = "#0%";

            this.chart1.ChartAreas[0].AxisX.Minimum = _estimatedHours / 2;
            this.chart1.ChartAreas[0].AxisX.Maximum = _estimatedHours * 2;

            this.chart1.ChartAreas[0].AxisX.Interval = 4;

            this.chart1.FormatNumber += chart1_FormatNumber;

            this.chart1.ChartAreas[0].CursorX.Interval = 0;
            this.chart1.ChartAreas[0].CursorY.Interval = 0;

            this.chart1.MouseMove += chart1_MouseMove;

            DrawGraph();
        }

        void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
        {
            if (e.ElementType != ChartElementType.AxisLabels)
                return;

            var axis = (Axis)sender;

            if (axis.AxisName != AxisName.X)
                return;

            e.LocalizedValue = formatTimeSpan(TimeSpan.FromHours(e.Value));
        }

        private string formatTimeSpan(TimeSpan timeSpan)
        {
            if (timeSpan.Days == 0)
                return timeSpan.ToString("h'h'");
            else
                if (timeSpan.Hours == 0)
                    return timeSpan.ToString("d'j'");
                else
                    return timeSpan.ToString("d'j + 'h'h'");
        }

        public void DrawGraph()
        {
            var _history = new HistoryOfVelocities();

            _history.GenerateFakeHistory();

            var probabilities = _history.SimulateTheFuture(_estimatedHours);

            var probabilityDensities = _history.ProbabilityDensities(probabilities);

            foreach (var probability in probabilityDensities)
            {
                var index =
                    this.chart1.Series[0].Points.AddXY(probability.Item1.TotalHours, probability.Item2);

                this.chart1.Series[0].Points[index].ToolTip = string.Format("Estimation: {1}\r\nProbabilité: {0:#0%}", probability.Item2, formatTimeSpan(probability.Item1));
            }
        }

        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {
            this.chart1.ChartAreas[0].CursorX.SetCursorPixelPosition(e.Location, true);
            this.chart1.ChartAreas[0].CursorY.SetCursorPixelPosition(e.Location, true);
        }
    }
}
